/**
 * Copyright (c) 快宝网络 kuaidihelp.com Co., Ltd. All Rights Reserved 禁止外泄以及用于其它的商业用途
 */

/* eslint-disable react/jsx-no-bind */
import React, { useCallback, useMemo, useEffect, useState } from 'react';
import { connect } from 'dva';
import { Button, Col, Form, Input, message, Row } from 'antd';
import StandardTable from '@/components/StandardTable';
import KbRangePicker, { key2Moment } from '@/components/KbRangePicker';
import { isLegalData } from '@/utils/utils';
import patterns from '@/utils/patterns';
import router from 'umi/router';
import moment from 'moment';
import PropTypes from 'prop-types';

const { phone } = patterns;

const inputMap = {
  scan: {
    label: '扫描员',
    placeholder: '请输入扫描员手机号或姓名',
  },
  send: {
    label: '派件员',
    placeholder: '请输入派件员手机号或姓名',
  },
};
const initDate = key2Moment('yesterday');
const initRanges = {
  yesterday: {
    date: initDate,
    name: '昨天',
  },
  beforeYesterday: {
    date: [
      moment(
        moment()
          .subtract(2, 'days')
          .format('YYYY-MM-DD'),
      ),
      moment(
        moment()
          .subtract(2, 'days')
          .format('YYYY-MM-DD'),
      ),
    ],
    name: '前天',
  },
  thisMonth: {
    date: [
      moment(
        moment()
          .startOf('month')
          .format('YYYY-MM-DD'),
      ),
      moment(
        moment()
          .subtract(1, 'days')
          .format('YYYY-MM-DD'),
      ),
    ],
    name: '本月',
  },
  lastMonth: {
    date: [
      moment(
        moment()
          .month(moment().month() - 1)
          .startOf('month')
          .format('YYYY-MM-DD'),
      ),
      moment(
        moment()
          .month(moment().month() - 1)
          .endOf('month')
          .format('YYYY-MM-DD'),
      ),
    ],
    name: '上月',
  },
};
const FormItem = Form.Item;

const jump = ({ brand, start_scan_time, end_scan_time, keyWords, hash, ...rest }) => {
  router.push({
    pathname: '/Allocation/GunScanRecord',
    hash: `#${hash === 'arrival' ? 'arrive' : hash}`,
    query: {
      brand: brand === 'sum' ? 'all' : brand,
      send_status: '1',
      start_scan_time,
      end_scan_time,
      courier: keyWords,
      cm_phone: keyWords,
      ...rest,
    },
  });
};

const renderChildren = ({ type, brand, queryData = {} }) => {
  // 派件统计不需要
  if (type === 'send') return [];

  const jumpTargetNameMap = {
    send: '发件',
    arrival: '到件',
    delivery: '派件',
    sign: '签收',
  };
  const jumpTargetArr = Object.keys(jumpTargetNameMap);

  return jumpTargetArr.map(val => ({
    title: jumpTargetNameMap[val],
    width: 100,
    align: 'center',
    key: `${brand}_${val}`,
    dataIndex: `${brand}[${val}]`,
    render: (text, { courier_phone }) => {
      if (text) {
        return (
          <a onClick={() => jump({ brand, hash: val, keyWords: courier_phone, ...queryData })}>
            {text}
          </a>
        );
      }
      return '-';
    },
  }));
};

const effectsType = {
  scan: {
    getList: 'dataStatistics/getScanList',
    downLoadURL: '/v1/TotalDistribution/MultiBrandQueryInfo/getSumTotalByCourier',
  },
  send: {
    getList: 'dataStatistics/getSendList',
    downLoadURL: '/v1/TotalDistribution/MultiBrandQueryInfo/getSumTotalByOperator',
  },
};

const DataStatisticsTemplate = ({
  form,
  type,
  dispatch,
  tableList,
  userInfo = {},
  options = {},
}) => {
  const { getFieldDecorator, validateFields, setFieldsValue } = form;
  const { branchId: branch_id } = userInfo;
  const { key } = options;

  const [brands, setBrands] = useState([]);
  const [loading, setLoading] = useState(false);
  const [searchValue, setSearchValue] = useState('');

  const columns = useMemo(
    () => {
      const queryData = (searchValue && JSON.parse(searchValue)) || {};
      const restColumns = brands.map(({ brand_name, brand_code }) => ({
        title: brand_name,
        dataIndex: brand_code,
        align: 'center',
        key: brand_code,
        width: 200,
        ...(type === 'send'
          ? {
              render: (brand, record) =>
                (brand && (
                  <a
                    onClick={() =>
                      jump({
                        brand: brand_code,
                        hash: 'delivery',
                        dispatch_phone: record.courier_phone,
                        ...queryData,
                      })
                    }
                  >
                    {brand.delivery}
                  </a>
                )) ||
                '-',
            }
          : { children: renderChildren({ type, brand: brand_code, queryData }) }),
      }));
      return [
        {
          title: type === 'send' ? '派件员' : '扫描员',
          dataIndex: 'courier_phone',
          align: 'center',
          key: 'courier_phone',
          fixed: 'left',
          width: 240,
          render: (text, record) => `${record.courier_name}-${text}`,
        },
        ...restColumns,
        {
          title: '汇总',
          dataIndex: 'sum',
          key: 'sum',
          align: 'center',
          width: 200,
          ...(type === 'send'
            ? {
                render: (sum, record) =>
                  (sum && (
                    <a
                      onClick={() =>
                        jump({
                          brand: 'sum',
                          hash: 'delivery',
                          dispatch_phone: record.courier_phone,
                          ...queryData,
                        })
                      }
                    >
                      {sum.delivery}
                    </a>
                  )) ||
                  '-',
              }
            : { children: renderChildren({ type, brand: 'sum', queryData }) }),
        },
      ];
    },
    [type, brands, searchValue],
  );

  const getFormValue = useCallback(
    (cb = () => {}) => {
      validateFields((err, values) => {
        if (err) return;
        const { scanDate = [], keyWords = '' } = values;
        const [start, end] = scanDate;
        const isPhone = phone.pattern.test(keyWords);
        const start_time = start.format('YYYY-MM-DD');
        const end_time = end.format('YYYY-MM-DD');

        if (start && end) {
          const inMonth = end.month() === start.month();
          const dayDiff = moment(end).diff(start, 'day');
          if (!inMonth) {
            message.warn('不支持跨月查询，请重新选择查询区间');
            return;
          }
          if (dayDiff > 31) {
            message.error('最大支持31天内的数据查询');
            return;
          }
        }

        setSearchValue(
          JSON.stringify({
            start_scan_time: start_time,
            end_scan_time: end_time,
          }),
        );
        cb({
          [isPhone ? 'courier_phone' : 'courier_name']: keyWords,
          start_time,
          end_time,
        });
      });
    },
    [validateFields],
  );

  const getList = useCallback(
    isExport => {
      getFormValue(values => {
        if (!isExport) {
          setLoading(true);
        }
        dispatch({
          type: effectsType[type].getList,
          payload: {
            ...values,
            n_export: isExport ? 1 : undefined,
          },
        })
          .then(() => {
            setLoading(false);
          })
          .catch(() => {
            setLoading(false);
          });
      });
    },
    [dispatch, type, getFormValue],
  );

  const onSubmit = useCallback(
    e => {
      e.preventDefault();
      getList();
    },
    [getList],
  );

  const getBrandsList = useCallback(
    () => {
      const payload = key == 'post' ? { branch_id } : {};
      dispatch({
        type: 'allocation/getTabList',
        payload,
      }).then(res => {
        const { data = [] } = res;
        let brandList = isLegalData(data);
        if (type === 'send') {
          brandList = isLegalData(data);
        }
        setBrands(brandList);
      });
    },
    [dispatch, type],
  );

  const onShortCutClick = rangeType => {
    const { date = [] } = initRanges[rangeType];
    setFieldsValue({
      scanDate: date,
    });
  };

  useEffect(
    () => {
      getBrandsList();
      return () => {
        dispatch({
          type: 'dataStatistics/save',
          payload: {
            scanList: {
              list: [],
            },
            sendList: {
              list: [],
            },
          },
        });
      };
    },
    [getBrandsList, dispatch],
  );

  return (
    <>
      <Form layout="inline" onSubmit={onSubmit} style={{ marginBottom: 24 }}>
        <FormItem label="扫描日期">
          {getFieldDecorator('scanDate', {
            initialValue: initDate,
            rules: [
              {
                required: true,
                message: '请选择扫描时间',
              },
            ],
          })(
            <KbRangePicker max={31} unit="day" disabledToday disableOutOfRange showTime={false} />,
          )}
          <Row type="flex" gutter={[20, 20]}>
            {Object.keys(initRanges).map(val => (
              <Col key={val}>
                <a onClick={() => onShortCutClick(val)}>{initRanges[val].name}</a>
              </Col>
            ))}
          </Row>
        </FormItem>
        <FormItem label={inputMap[type].label}>
          {getFieldDecorator('keyWords')(
            <Input allowClear style={{ width: 250 }} placeholder={inputMap[type].placeholder} />,
          )}
        </FormItem>
        <FormItem>
          <Button type="primary" htmlType="submit" loading={loading}>
            查询
          </Button>
        </FormItem>
        <FormItem>
          <Button
            disabled={tableList.list.length == 0}
            type="primary"
            onClick={getList.bind(null, true)}
          >
            导出
          </Button>
        </FormItem>
      </Form>
      <StandardTable
        rowKey={record => (type === 'send' ? record.phone : record.courier_phone)}
        loading={loading}
        data={tableList}
        columns={columns}
        scroll={{ x: 800 }}
      />
    </>
  );
};

DataStatisticsTemplate.propTypes = {
  type: PropTypes.oneOf(['scan', 'send']).isRequired,
};

export default connect(({ dataStatistics, loading, user, setting }, { type }) => ({
  tableList: dataStatistics[`${type}List`],
  userInfo: user.currentUser.user_info,
  options: setting.options,
  loading: loading.effects['dataStatistics/getScanList'],
}))(React.memo(Form.create()(DataStatisticsTemplate)));
